package com.xnet.shiro.service.base.impl;

import com.xnet.base.service.impl.BaseServiceImpl;
import com.xnet.common.entity.*;
import com.xnet.shiro.entity.base.DepartmentEntity;
import com.xnet.shiro.entity.base.OrganizeEntity;
import com.xnet.shiro.manager.base.UserManager;
import com.xnet.common.utils.CommonUtils;
import com.xnet.common.utils.MD5Utils;
import com.xnet.shiro.service.base.DepartmentService;
import com.xnet.shiro.service.base.OrganizeService;
import com.xnet.shiro.service.base.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 系统用户
 *
 * @author Xingyc
 * @date 2018-1-11 14:48:54
 */
@Service("sysUserService")
public class UserServiceImpl extends BaseServiceImpl<UserEntity> implements UserService {

    @Autowired
    private UserManager userManager;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private OrganizeService organizeService;

    @Override
    public Page<UserEntity> listUser(Map<String, Object> params) {

        Query form = new Query(params);
        Page<UserEntity> page = new Page<>(form);
        userManager.listUser(page, form);
        return page;
    }

    /**
     * 新增保存
     * @param entity
     * @return
     */
    @Override
    public R saveUser(UserEntity entity) {
        create(entity);
        int count = userManager.saveUser(entity);
        return CommonUtils.msg(count);
    }

    /**
     * 根据id获取用户实体
     * @param userId
     * @return
     */
    @Override
    public R getUserById(String userId) {
        UserEntity user = userManager.getById(userId);
        return CommonUtils.msg(user);
    }

    /**
     * 编辑保存
     * @param entity
     * @return
     */
    @Override
    public R updateUser(UserEntity entity) {
        modify(entity);
        int count = userManager.updateUser(entity);
        return CommonUtils.msg(count);
    }

    /**
     * 批量删除
     * @param id
     * @return
     */
    @Override
    public R batchRemove(String[] id) {

        int count = userManager.batchRemove(id);
        return CommonUtils.msg(count);
    }

    /**
     * 获取用户权限
     * @param userId
     * @return
     */
    @Override
    public R listUserPerms(String userId) {

        Set<String> perms = userManager.listUserPerms(userId);
        return CommonUtils.msgNotCheckNull(perms);
    }

    /**
     * 首页密码修改
     * @param user
     * @return
     */
    @Override
    public R updatePswdByUser(UserEntity user) {

        String username = user.getAccount();
        String pswd = user.getPassword();
        String newPswd = user.getEmail();
        pswd = MD5Utils.encrypt(username, pswd);
        newPswd = MD5Utils.encrypt(username, newPswd);
        Query query = new Query();
        query.put("userId", user.getUserId());
        query.put("password", pswd);
        query.put("newPassword", newPswd);
        int count = userManager.updatePswdByUser(query);
        if (!CommonUtils.isIntThanZero(count)) {
            return R.error("原密码错误");
        }
        return CommonUtils.msg(count);
    }

    /**
     * 修改用户可用状态
     * @param id
     * @return
     */
    @Override
    public R updateUserEnable(String[] id) {

        int count = userManager.updateUserEnable(id);
        return CommonUtils.msg(id, count);
    }

    /**
     * 修改用户禁用状态
     * @param id
     * @return
     */
    @Override
    public R updateUserDisable(String[] id) {

        int count = userManager.updateUserDisable(id);
        return CommonUtils.msg(id, count);
    }

    /**
     * 重置密码
     * @param user
     * @return
     */
    @Override
    public R updatePswd(UserEntity user) {

        UserEntity currUser = userManager.getUserById(user.getUserId());
        user.setPassword(MD5Utils.encrypt(currUser.getAccount(), user.getPassword()));
        int count = userManager.updatePswd(user);
        return CommonUtils.msg(count);
    }

    /**
     * 实体创建初始化
     * @param entity
     */
    @Override
    public void create(UserEntity entity)
    {
        super.create(entity);
        entity.setDeleteMark(0);
        entity.setEnabledMark(1);
        String userId= UUID.randomUUID().toString();
        entity.setUserId(userId);
        entity.setPassword(MD5Utils.encrypt(entity.getAccount(), entity.getPassword()));
    }

    /**
     * 实体修改初始化
     * @param entity
     */
    @Override
    public void modify(UserEntity entity)
    {
        super.modify(entity);
    }


    /**
     * 获取机构+部门+用户列表树
     *
     * @return
     */
    public List<TreeEntity> getOrganizeDepartmentUserTreelist() {
        //获取所有机构列表
        List<OrganizeEntity> allOrgList = organizeService.getListTree(null);

        //获取所有部门列表
        List<DepartmentEntity> allDeptList = departmentService.getListTree(null, null);

        //组合机构+部门 并转换为树形实体列表
        List<TreeEntity> allOrgDeptTreeList = departmentService.convertOrganizeToTreeList(allOrgList, allDeptList,false);

        //获取所有用户列表（非管理员及可用状态的用户）
        List<UserEntity> allUserList = userManager.listAllUser();

        //将用户追加到机构部门树节点上
        for (UserEntity item : allUserList) {
            TreeEntity tree = new TreeEntity();
            boolean hasChildren = false;
            tree.setId(item.getUserId());
            tree.setText(item.getRealName());
            tree.setValue(item.getAccount());
            tree.setIsExpand(true);
            tree.setComplete(true);
            tree.setHasChildren(hasChildren);
            tree.setParentId(item.getDepartmentId());
            tree.setTitle(item.getRealName() + "（" + item.getAccount() + "）");
            //增加属性
            tree.setAttribute("Sort");
            tree.setAttributeValue("User");
            tree.setImg("fa fa-user");
            allOrgDeptTreeList.add(tree);
        }
        return allOrgDeptTreeList;
    }

    /**
     * 根据部门获取人员列表
     * @return
     */
    @Override
    public List<UserEntity> getListByDepartmentId(String departmentId)
    {
        return userManager.getListByDepartmentId(departmentId);
    }

    /**
     * 根据非管理员之外所有用户列表
     * @return
     */
    @Override
    public List<UserEntity> listAllUser(){
        return userManager.listAllUser();
    }
}
